import React from 'react';
import { connect } from 'react-redux';
import BaseComponent from '../../components/common/baseComponent.js';
import Button from '../../components/common/button';
import CouponSelectModal from '../../components/coupon/couponSelectModal';
import { getQueryParam } from '../../utils/url';
import CouponCell from '../../components/coupon/couponCell';
import toast from '../../utils/toast';
import CouponAlertModal from '../../components/coupon/couponAlertModal';
import { debounced } from '../../utils/func';
import youyuIcon from '../../../assets/images/pay/youyu.png';
import wechatIcon from '../../../assets/images/pay/wechat.png';
import { inWechat } from '../../utils/wechat';

@connect(({
  coupon,
  loading,
  user,
}) => {
  const couponList = coupon.get('payCouponList');
  const balance = user.getIn(['account', 'balance']);
  return {
    couponList,
    balance,
    maxSelect: coupon.get('maxSelect'),
    disabled: ['pay/fetchPayModeIfNeeded', 'coupon/fetchAndCalPayCoupon'].some(action => loading.effects[action]),
    loading: ['refuel/refuel', 'pay/prePay', 'pay/doPay'].some(action => loading.effects[action]),
  };
})
class Pay extends BaseComponent {
  state = {
    money: getQueryParam('money'),
    oil: getQueryParam('oil'),
    mchId: getQueryParam('mchId'),
    gun: getQueryParam('gun'),
    stationId: getQueryParam('stationId'),
    selectCash: true,
    selectBalance: false,
  }
  componentDidMount() {
    const { mchId, money } = this.state;
    this.props.dispatch({
      type: 'coupon/fetchAndCalPayCoupon',
      payload: {
        money,
        listParams: {
          mchId,
          source: window.source,
        },
        calParams: {
          amount: parseInt(Number(money) * 100, 10),
          mchId,
          ownSelectIds: [],
          source: window.source,
        },
      },
    });
    this.props.dispatch({
      type: 'user/fetchBalance',
    });
  }

  clickPay = debounced(() => {
    console.log('click pay');
    const { money, selectCash, selectBalance } = this.state;
    const {
      balance,
    } = this.props;
    if (!selectBalance && !selectCash) {
      toast('请选择支付方式');
    } else if (selectBalance && !selectCash && Number(balance) < Number(money)) {
      toast('余额不足以支付该笔订单, 请重新选择支付方式');
    } else {
      this.doPay();
    }
  }, 300)

  closeAlert = () => {
    const { couponList } = this.props;
    const { money } = this.state;
    const selectedCouponList = couponList.filter(coupon => coupon.get('selected'));
    const tmallAmount = selectedCouponList.filter(coupon => coupon.isTmall()).reduce((amount, coupon) => {
      return amount + coupon.get('giftAmount');
    }, 0) / 100;
    this.alert.close();
    if (Number(tmallAmount) > Number(money)) {
      this.doPay();
    }
  }

  doPay = () => {
    const { couponList } = this.props;
    const selectedCouponList = couponList.filter(coupon => coupon.get('selected'));
    const {
      money,
      oil,
      gun,
      // mchId,
      stationId,
      selectCash,
      selectBalance,
    } = this.state;
    const payModes = [];
    let prePayMode;
    if (selectedCouponList.size > 0 && !selectBalance) {
      payModes.push(3);
    }
    if (selectBalance) {
      payModes.push(1);
    }
    if (selectCash) {
      payModes.push(2);
      prePayMode = inWechat() ? 'WECHATPUBLIC' : 'WECHATH5';
    }

    this.props.dispatch({
      type: 'refuel/refuel',
      payload: {
        amount: money,
        couponIdList: !selectBalance ? selectedCouponList.map(coupon => coupon.get('id')).toJS() : [],
        gunNo: gun,
        oilno: oil,
        payModes,
        gasStationId: stationId,
        prePayMode,
      },
    });
  }

  showCouponModal = () => {
    this.props.dispatch({
      type: 'coupon/sortCouponList',
    });
    this.modal.show();
  }

  selectCoupon = (coupon) => {
    const { money } = this.state;
    this.props.dispatch({
      type: 'coupon/selectRefuelCoupon',
      payload: {
        selectCoupon: coupon,
        number: money,
      },
    });
  }

  selectCouponDone = () => {
    this.modal.close();
  }

  selectPayMode = (pm) => {
    const selectCash = pm === 'cash' ? !this.state.selectCash : false;
    const selectBalance = pm === 'balance' ? !this.state.selectBalance : false;
    this.setState({
      selectCash,
      selectBalance,
    });
  }

  render() {
    const {
      couponList,
      maxSelect,
      loading,
      disabled,
      balance,
    } = this.props;

    const { money, selectCash, selectBalance } = this.state;

    const balanceView = (
      <div className="pay-cell" onClick={() => this.selectPayMode('balance')}>
        <img src={youyuIcon} alt="" className="icon" />
        <div className="title">余额支付</div>
        <div className="text">可用余额&#65509;{balance}</div>
        <i className={`iconfont icon-checkbox ${selectBalance ? 'icon-checked' : 'icon-unchecked'}`} />
      </div>
    );
    const cashView = (
      <div className="pay-cell" onClick={() => this.selectPayMode('cash')}>
        <img src={wechatIcon} alt="" className="icon" />
        <div className="title">微信支付</div>
        <i className={`iconfont icon-checkbox ${selectCash ? 'icon-checked' : 'icon-unchecked'}`} />
      </div>
    );


    const selectedCouponList = couponList.filter(coupon => coupon.get('selected'));

    let couponView;

    const showCoupon = !selectBalance;

    if (showCoupon) {
      const couponCells = selectedCouponList.map((coupon, index) => {
        return <CouponCell coupon={coupon} key={index} />;
      });
      couponView = (
        <div className="coupon-view" onClick={this.showCouponModal}>
          <div className="title-row">
            <div className="title">加油优惠券</div>
            <p className="text">已选择<span className="num">{selectedCouponList.size}</span>张</p>
            <i className="iconfont icon-arrow" />
          </div>
          {couponCells}
        </div>
      );
    }

    const couponDis = showCoupon ? Math.min(selectedCouponList.reduce((total, coupon) => {
      return total + (coupon.get('giftAmount') / 100);
    }, 0), money) : 0;

    let couponMoney;
    if (couponDis > 0) {
      couponMoney = <p className="dis">优惠券抵扣{couponDis.toFixed(2)}元</p>;
    }

    const balancePay = selectBalance ? Math.min(money - couponDis, balance) : 0;

    let balanceMoney;
    if (selectBalance) {
      balanceMoney = (<p className="dis">鱿鱼账户支付{balancePay.toFixed(2)}元</p>);
    }

    const payAmount = Number(money) - couponDis;

    return (
      <div className="pay">
        <div className="content">
          <div className="order-info-view">
            <div className="title">支付金额</div>
            <div className="money-row"><div className="unit">&#65509;</div><div className="money">{payAmount.toFixed(2)}</div></div>
            {balanceMoney}
            {couponMoney}
          </div>
          <div className="pay-view">
            {balanceView}
            {cashView}
          </div>
          {couponView}
        </div>
        <Button title="立即支付" className="pay-btn" clickFunc={this.clickPay} loading={loading} disabled={disabled} />
        <CouponSelectModal
          ref={modal => this.modal = modal}
          couponList={couponList}
          selectFunc={this.selectCoupon}
          confirmFunc={this.selectCouponDone}
          maxSelect={maxSelect}
        />
        <CouponAlertModal ref={alert => this.alert = alert} closeFunc={this.closeAlert} />
      </div>
    );
  }
}

export default Pay;
